import Koa from 'koa';
import koaBody from 'koa-body';
import router from '../router';
import midSend from './send';
import onerror from 'koa-onerror';
import koaStatic from 'koa-static';
import { jwtMiddleware } from './jwt';
import { uploadBasePath } from '../config/app';

export const middleware = (app: Koa) => {
  onerror(app, {
    // 统一错误处理
    all(error: Error, ctx: Koa.Context) {
      ctx.set('Content-Type', 'application/json');
      ctx.body = JSON.stringify({
        code: 500,
        msg: error,
      });
    },
  });

  app.use(midSend());

  jwtMiddleware(app);

  app.use(
    koaBody({
      formLimit: '3mb',
      multipart: true, // Allow multiple files to be uploaded
      formidable: {
        maxFileSize: 200 * 1024 * 1024, // Upload file size
        keepExtensions: true, //  Extensions to save images
      },
    })
  );

  app.use(koaStatic(uploadBasePath));

  router(app);
};
